package com.vito.base.authoriza.action;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONArray;
import com.vito.base.authoriza.cache.SessionMap;
import com.vito.base.authoriza.model.DeptModel;
import com.vito.base.authoriza.model.UserModel;
import com.vito.base.authoriza.service.DeptService;
import com.vito.base.authoriza.service.SectionService;
import com.vito.base.exception.ParamErrorException;
import com.vito.base.model.DataGrid;
import com.vito.base.model.Result;
import com.vito.base.tools.I18nResMsg;
import com.vito.base.util.Contants;
import com.vito.base.util.StringUtil;
import com.vito.base.util.Validata;
import com.vito.dcs.section.model.SectionModel;

@Controller
@RequestMapping("base/authoriza/dept")
public final class DeptAction extends BaseAction {
	
	private static final Logger log = LoggerFactory.getLogger(DeptAction.class);
	
	@Reference
	private SectionService sectionService;
	
	
	@RequestMapping("getTree")
	@ResponseBody
	public Result queryTree(DeptModel dept){
		Result res = new Result();
		try{
			SessionMap.putUserInfo(dept);
			List<DeptModel> depts = deptServiceImpl.queryDeptTree(dept);
			if(depts!=null&&depts.size()>0){
				res.setData(depts);
				res.setCode(Result.CODE_OK);
			}else{
				res.setCode(Result.CODE_NO_DATA);
			}
		}catch(Exception ex){
			log.error("查询异常",ex);
			res.setCode(Result.CODE_ERROR);
			//res.setMsg(I18nMessage.getMessage(DeptContants.ABNORMAL(),DeptContants.QUERY()));
			res.setMsg(I18nResMsg.EXECERR());
		}
		return res;
	}
	
	@RequestMapping("getTreeall")
	@ResponseBody
	public Result queryAsyncTree(@RequestParam Map<String,Object> dept,String[] systypes,String[] checkeds){
		Result res = new Result();
		try{
			SessionMap.putUserInfo(dept);
			
			dept.put("systypes", systypes);
			dept.put("checkeds",checkeds);
			
			List<DeptModel> depts = deptServiceImpl.queryTreeAll(dept);
			if(depts!=null&&depts.size()>0){
				res.setData(depts);
				res.setCode(Result.CODE_OK);
			}else{
				res.setCode(Result.CODE_NO_DATA);
			}
		}catch(Exception ex){
			log.error("查询异常",ex);
			res.setCode(Result.CODE_ERROR);
			//res.setMsg(I18nMessage.getMessage(DeptContants.ABNORMAL(),DeptContants.QUERY()));
			res.setMsg(I18nResMsg.EXECERR());
		}
		return res;
	}
	
	@ResponseBody
	@RequestMapping("findDeptTreeByUserId")
	public Result findDeptTreeByUserId(Map<String,String> map){
		Result rs = new Result();
		try {
			UserModel user = (UserModel)SessionMap.getObj();
			String userId = user.getUserId();
			map.put("user_id", userId);
			List<DeptModel> list = deptServiceImpl.findDeptTreeByUserId(map);
			if(list!=null && list.size()>0){
				rs.setData(list);
				rs.setCode(Result.CODE_OK);
			}else{
				rs.setCode(Result.CODE_NO_DATA);
			}
		} catch (Exception e) {
			log.error("查询异常",e);
			rs.setCode(Result.CODE_ERROR);
			//rs.setMsg(I18nMessage.getMessage(DeptContants.ABNORMAL(),DeptContants.QUERY()));
			rs.setMsg(I18nResMsg.EXECERR());
		}
		return rs;
	}
	
	@Reference
	private DeptService deptServiceImpl ;

	@RequestMapping("save")
	@ResponseBody
	public Result saveDept(DeptModel dept){
		Result res = new Result();
		try{
			//非超级管理员 需要选择父级部门
			if(SessionMap.getObj().getUserType()<Contants.ADMIN_USER_TYPE){
				if(dept.getDeptParent()==null||"".equals(dept.getDeptParent())){
					res.setCode(Result.CODE_PARA_ERROR);
					res.setMsg(DeptContants.PARENT());	
					return res;
				}
			}
			
			if(SessionMap.getObj() == null || Validata.isNullOrEmpty(SessionMap.getObj().getUserId())){
				res.setCode(Result.CODE_LOGIN_REQUIRE);
				res.setMsg(I18nResMsg.MSG_LOGIN_NEED());	
				return res;
			}
			
			SessionMap.putUserInfo(dept);
			
			
			if("2".equals(dept.getBase_name())){
				
				String des = dept.getDes();
				List parse = (List) JSONArray.parse(des);
				
				SectionModel secModel = new SectionModel();
				secModel.setSectionId(dept.getDeptParent());
				/**
				 * 拿到所有的Id，和查询的比对
				 */
				List<SectionModel> queryWorkArea = sectionService.queryWorkArea(secModel );
				
				String[] store = null;
				if(queryWorkArea != null && queryWorkArea.size() > 0){
					store = new String[queryWorkArea.size()];
					for (int i = 0; i < queryWorkArea.size(); i ++) {
						store[i] = queryWorkArea.get(i).getSectionId();
					}
				}
				String[] trans = null;
				if(parse != null && parse.size() > 0){
					trans = new String[parse.size()];
					for (int i = 0; i < parse.size(); i ++) {
						Map<String,String> m = (Map<String, String>) parse.get(i);
						if(!Validata.isNullOrEmpty(m.get("deptId"))){
							trans[i] = m.get("deptId");
						}
					}
				}
				List<String> newCK = new ArrayList<String>();
				if(store != null && store.length > 0){
					List<String> asList = Arrays.asList(store);
					List<String> asList2 = Arrays.asList(trans);
					for(int i = 0; i < asList.size(); i ++){
						if(!asList2.contains(asList.get(i))){
							newCK.add(asList.get(i));
						}
					}
					
				}
				
				/**
				 * 执行更新(逻辑删除)
				 */
				if(newCK.size() > 0){
					secModel.setTransList(newCK);
					int queryIsHaveVehicle = sectionService.queryIsHaveVehicle(secModel);
					if(queryIsHaveVehicle > 0){
						res.setCode(Result.CODE_PARA_ERROR);
						res.setMsg("所删除的工区下存在关联车辆，不允许删除");
						return res;
					}
				}
			}
			deptServiceImpl.saveDept(dept);
			res.setCode(Result.CODE_OK);
			res.setData(dept);
			//res.setMsg(I18nMessage.getMessage(DeptContants.SUCCESS(),DeptContants.SAVE()));
			res.setMsg(I18nResMsg.SAVESUC());
		}catch(Exception ex){
			log.error("保存失败",ex);
			res.setMsg(I18nResMsg.SAVEERR());
			res.setCode(Result.CODE_ERROR);
		}
		return res ;
	}
	@RequestMapping("saveDeptRole")
	@ResponseBody
	public Result saveDeptRole(DeptModel dept){
		Result res = new Result();
		try{
			deptServiceImpl.saveDeptRole(dept);
			res.setCode(Result.CODE_OK);
			res.setData(dept);
			res.setMsg(I18nResMsg.SAVESUC());
		}catch(Exception ex){
			log.error("保存失败",ex);
			res.setMsg(I18nResMsg.SAVEERR());
			res.setCode(Result.CODE_ERROR);
		}
		return res ;
	}
	@RequestMapping("update")
	@ResponseBody
	public Result updateDept(DeptModel dept){
		Result res = new Result();
		
		try{
			UserModel user = SessionMap.getObj();
			if(user==null){
				res.setCode(Result.CODE_LOGIN_REQUIRE);
				res.setMsg(I18nResMsg.MSG_LOGIN_NEED());
				return res;
			}
			//非管理员 需要选择父级部门
			if(SessionMap.getObj().getUserType()<Contants.ADMIN_USER_TYPE){
				if(dept.getDeptParent()==null||"".equals(dept.getDeptParent())){
					res.setCode(Result.CODE_PARA_ERROR);
					res.setMsg(DeptContants.PARENT());	
					return res;
				}
			}
			SessionMap.putUserInfo(dept);
			
			deptServiceImpl.updateDept(dept);
			res.setCode(Result.CODE_OK);
			res.setData(dept);
			res.setMsg(I18nResMsg.UPDSUC());
		}catch(Exception ex){
			log.error("更新失败",ex);
			res.setMsg(I18nResMsg.UPDERR());
			res.setCode(Result.CODE_ERROR);
		}
		return res ;
	}

	@RequestMapping("delete")
	@ResponseBody
	public Result deleteDept(DeptModel dept){
		Result res = new Result();
		try{
			SessionMap.putUserInfo(dept);
			
			deptServiceImpl.deleteDept(dept);
			
			res.setCode(Result.CODE_OK);
			res.setData(dept);
			res.setMsg(I18nResMsg.DELSUC());
		}catch(ParamErrorException e){
			res.setMsg(e.getMessage());
			res.setCode(Result.CODE_PARA_ERROR);
		}catch(Exception ex){
			log.error("删除失败",ex);
			res.setMsg(I18nResMsg.DELERR());
			res.setCode(Result.CODE_ERROR);
		}
		return res ;
	}
	@RequestMapping("getByPaged")
	@ResponseBody
	public Result queryByPage(@RequestParam Map<String,Object> dept) {
		Result res = new Result();
		try{
			SessionMap.putUserInfo(dept);
			if(dept.containsKey("deptParent")&&!StringUtil.isEmpty(dept.get("deptParent").toString())){
				dept.put("deptParentCode", deptServiceImpl.queryDeptCodeById(dept.get("deptParent").toString()));
			}
			DataGrid<DeptModel> page = deptServiceImpl.queryDeptByPage(dept);
			if(page.getTotal()!=0){
				res.setCode(Result.CODE_OK);
				res.setData(page);
			}else{
				res.setCode(Result.CODE_NO_DATA);
				res.setMsg(DeptContants.NO_DATA());
			}
		}catch(Exception ex){
			log.error("查询异常",ex);
			res.setCode(Result.CODE_ERROR);
			res.setMsg(I18nResMsg.EXECERR());
		}
		return res ;
	}
	@RequestMapping("queryDeptTreeByRootDept")
	@ResponseBody
	public Result queryDeptTreeByRootDept() {
		Result res = new Result();
		try{
			UserModel user = SessionMap.getObj();
			if(user==null||Validata.isNullOrEmpty(user.getUserId())){
				res.setCode(Result.CODE_LOGIN_REQUIRE);
				res.setMsg(I18nResMsg.MSG_LOGIN_NEED());
				return res;
			}
			if(!Validata.isNullOrEmpty(user.getDeptParentId())){
				res.setCode(Result.CODE_OK);
				res.setData(deptServiceImpl.queryDeptTreeByRootDept(user.getDeptParentId()));
			}else{
				res.setCode(Result.CODE_NO_DATA);
				res.setMsg(DeptContants.NO_DATA());
			}
		}catch(Exception ex){
			log.error("查询异常",ex);
			res.setCode(Result.CODE_ERROR);
			res.setMsg(I18nResMsg.EXECERR());
		}
		return res ;
	}
//	@RequestMapping("queryDeptParents")
//	@ResponseBody
//	public Result queryDeptParents(String deptId) {
//		Result res = new Result();
//		try{
//			UserModel user = SessionMap.getObj();
//			if(user==null||Validata.isNullOrEmpty(user.getUserId())){
//				res.setCode(Result.CODE_LOGIN_REQUIRE);
//				res.setMsg(ResMsg.MSG_LOGIN_NEED);
//				return res;
//			}
//			if(!Validata.isNullOrEmpty(deptId)){
//				res.setCode(Result.CODE_OK);
//				res.setData(deptServiceImpl.queryDeptParents(deptId));
//			}
//		}catch(Exception ex){
//			log.error("查询异常",ex);
//			res.setCode(Result.CODE_ERROR);
//			res.setMsg("查询异常");
//		}
//		return res ;
//	}
}



